#include "checa_status.h"

void *thread(void *v)
{
	int i = 0, j = 0;
	
	thr_Handler thrh = *((thr_Handler *) v);
	p_parteTabuleiro t = thrh.t;
	/* calculaProxGen(t, thrh.x, thrh.y); */
	for(i = 0; i < t->size_y; i++)
		for(j = 0; j < t->size_x; j++)
			if(checa_status((t->tabuleiro[t->matriz_ger_atual]), t->x+j, t->y+i, thrh.x, thrh.y))
				(t->tabuleiro)[!t->matriz_ger_atual][t->y+i][t->x+j] = TAB_MARK;
			else
				(t->tabuleiro)[!t->matriz_ger_atual][t->y+i][t->x+j] = TAB_NOMARK;
	return NULL;
}

void getNextGen(p_parteTabuleiro t, int x, int y)
{
	int i = 0, j = 0, d_larg = 0, d_alt = 0, larg_ult = 0, alt_ult = 0;
	pthread_t thr[THREADS_Y][THREADS_X];
	thr_Handler h[THREADS_Y][THREADS_X];
	t_parteTabuleiro thread_t[THREADS_Y][THREADS_X];
	
	d_larg = floor(x / THREADS_X);
	d_alt = floor(y / THREADS_Y);
	larg_ult = x - (THREADS_X - 1) * d_larg;
	alt_ult = y - (THREADS_Y - 1) * d_alt;
	
	for (i = 0; i < THREADS_X; i++)
	{
		for (j = 0; j < THREADS_Y; j++)
		{
			thread_t[j][i].x = i * d_larg;
			thread_t[j][i].y = j * d_alt;
			
			if (i == THREADS_X-1)
				thread_t[j][i].size_x = larg_ult;
			else
				thread_t[j][i].size_x = d_larg;
			
			if (j == THREADS_Y-1)
				thread_t[j][i].size_y = alt_ult;
			else
				thread_t[j][i].size_y = d_alt;
			
			thread_t[j][i].matriz_ger_atual = t->matriz_ger_atual;
			thread_t[j][i].tabuleiro = t->tabuleiro;
			h[j][i].t = &(thread_t[j][i]);
			h[j][i].x = x;
			h[j][i].y = y;
			
			pthread_create(&(thr[j][i]), NULL, thread, (void *)&(h[j][i]));
		}
	}
		
	for (i = 0; i < THREADS_X; i++)
		for (j = 0; j < THREADS_Y; j++)
			pthread_join(thr[j][i], NULL);
	t->matriz_ger_atual = !t->matriz_ger_atual;
}
